<?php


namespace App\Services;


use App\Http\Controllers\DriverApp\Utils;
use App\Models\User;
use App\Repositories\UserRepository;
use Illuminate\Auth\Events\Validated;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Validator;

class UsersService extends BaseService
{
    protected $model;
    protected $repository;

    function __construct()
    {
        $this->model = new User();
        $this->repository = new UserRepository();
    }

    /**
     * @param string $phone
     * @param string $password
     * @param string $type
     * @return array
     * @throws \App\Exceptions\BobException
     */
    public function user_login(string $phone, string $password, string $type, $code)
    {
        $user = $this->model->first('phone', $phone);
        if (!$user) return_bob('该手机尚未注册');
        if ($type == 2) {
            if (Cache::get($phone) != $code) return_bob('验证码不正确,请重新输入');
        } else {
            if (bcrypt($password) != $user->password) return_bob('密码不正确,请重新输入');
        }
        return self::user_info($user);
    }

    /**
     * @param string $phone
     * @param string $password
     * @param string $code
     */
    public function reg(string $phone, string $password, string $code)
    {
        $user = $this->model->first('phone', $phone);
        if ($user) return_bob('该手机以注册');

    }

    /**
     * @param User $user
     * @return array
     * @throws \App\Exceptions\BobException
     */
    protected function user_info(User $user): array
    {
        // 直接创建token并设置有效期
        $info = Db::table('users')->where('phone', $user->phone)->first();
        $token = Utils::CreateTokenByUserId($info->id);
        return [
            'token' => $token,
            'user' => [
                'name' => $info->name,
                'phone' => $user->phone,
                'avatar' => $info->avatar,
            ],
        ];
    }

    /**
     * @param $id
     * @param $attributes
     * @return bool|int
     */
    public function update($id, $attributes)
    {
        if ($attributes['password'] != $attributes['password1']) {
            return_bob('两次输入密码不一致');
        }
        unset($attributes['password1']);
        return $this->model->where('id', $id)->update($attributes);
    }


    /**
     * 保存乘客信息
     * @param array $data
     * @return bool
     * @Author 姿势就是力量
     */
    public function saveUser(array $data)
    {
        if (!isset($data['nick_name']) || !$data['nick_name']) {
            return $this->setError('请填写乘客昵称');
        }

        if (!isset($data['phone']) || !$data['phone']) {
            return $this->setError('请填写乘客手机号');
        }

        if (!isset($data['company_id']) || !$data['company_id']) {
            return $this->setError('请选择公司');
        }
        $user = $this->repository->saveData($data);
        if (!$user) return $this->setError('保存失败');

        return true;
    }


}